package com.worktool;

import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.selenium.CookieInterceptor;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RequestCallback;
import org.springframework.web.client.RestTemplate;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

/**
 * RestTemplate 初始化信息类
 * */
public class RestTemplateConfig {

	public RestTemplate restTemplate() {
		final RestTemplate restTemplate = new RestTemplate(this.okHttp3ClientHttpRequestFactory());
		List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
		//添加 fastjson 消息接受
		messageConverters.add(new FastJsonHttpMessageConverter());
		restTemplate.setMessageConverters(this.updateMessageConverters(messageConverters));
		return restTemplate;
	}
	
	public ClientHttpRequestFactory okHttp3ClientHttpRequestFactory() {
		// 设置连接池参数, 最大空闲连接数200, 空闲连接存活时间10s
		ConnectionPool connectionPool = new ConnectionPool(200, 10, TimeUnit.SECONDS);
		OkHttpClient okHttpClient = new OkHttpClient.Builder() //
				.retryOnConnectionFailure(false) //
				.connectionPool(connectionPool) //
				.connectTimeout(1000, TimeUnit.SECONDS) // 10s
				.readTimeout(1000, TimeUnit.SECONDS) // 10s
				.writeTimeout(1000, TimeUnit.SECONDS) // 10s
				.build();
		return new OkHttp3ClientHttpRequestFactory(okHttpClient);
	}
	
	/**
	 * 更新默认消息转换器
	 *
	 * @param messageConverters
	 * @return
	 */
	private List<HttpMessageConverter<?>> updateMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
		final Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
		while (iterator.hasNext()) {
			final HttpMessageConverter<?> converter = iterator.next();			
			if (converter instanceof StringHttpMessageConverter) {
				// 使用 "utf-8" 替换默认的 "ISO-8859-1" 消息转换器
				((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
			}			
		}
		return messageConverters;
	}


}
